using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;

public partial class post : BlogEngine.Core.Web.Controls.BlogBasePage
{
	public Post Post { get; private set; }

	protected void Page_PreInit(object sender, EventArgs e)
	{
		string slug = Request.QueryString["slug"];

		if (String.IsNullOrEmpty(slug))
			throw new HttpException(404, "Post not found.");

		Post = Post.GetPostBySlug(slug);

		if (Post == null)
			throw new HttpException(404, "Post not found.");

		if (!Post.IsVisible && !Page.User.Identity.IsAuthenticated)
			throw new HttpException(403, "Post no longer is here.");
	}

	protected void Page_Init(object sender, EventArgs e)
	{
		if (Post != null)
		{
			string path = Utils.RelativeWebRoot + "themes/" + BlogSettings.Instance.Theme + "/PostView.ascx";

			PostViewBase themedPostView = (PostViewBase)LoadControl(path);
			themedPostView.Post = Post;
			themedPostView.Location = ServingLocation.SinglePost;

			postView.Controls.Add(themedPostView);

			Page.Title = Server.HtmlEncode(Post.Title);

			AddMetaKeywords();
			AddMetaDescription();
			AddGenericLink("first", Post.Posts[0].Title, Post.Posts[0].PermaLink.ToString());
			AddGenericLink("last", Post.Posts[Post.Posts.Count - 1].Title, Post.Posts[Post.Posts.Count - 1].PermaLink.ToString());

			if (BlogSettings.Instance.EnablePingBackReceive)
				Response.AppendHeader("x-pingback", "http://" + Request.Url.Authority + Utils.RelativeWebRoot + "pingback.axd");
		}
	}

	/// <summary>
	/// Adds the post's description as the description metatag.
	/// </summary>
	private void AddMetaDescription()
	{
		if (!String.IsNullOrEmpty(Post.Description))
			base.AddMetaTag("description", Server.HtmlEncode(Post.Description));
		else if (!String.IsNullOrEmpty(Post.Content))
			base.AddMetaTag("description", Server.HtmlEncode(Post.Content.Substring(0, Math.Min(100, Post.Content.Length))));
	}

	/// <summary>
	/// Adds the post's tags as meta keywords.
	/// </summary>
	private void AddMetaKeywords()
	{
		base.AddMetaTag("keywords", Server.HtmlEncode(Post.Keywords));
	}
}